#!/bin/bash

DEVTOOLS=.devtools
# C C++ OC files
SOURCE_SUFFIX='\.(h|c|cpp|cc|hpp|cxx|hxx|m|mm|js)$'

# bash case insensitive match
shopt -s nocasematch

# clang-format
if ! command -v clang-format >/dev/null 2>&1; then
  cat >&2 <<EOF
clang-format not fond, abort git commit.
please install clang-format first, then commit again.

mac     -> brew install clang-format
windows -> http://llvm.org/builds/
ubuntu  -> sudo apt install clang-format

EOF
  exit 1
fi

function regenerateVersionHeader() {
  VERSION_STRING=$(cat VERSION)
  IFS='.' read -a VERSION_ARRAY <<<"${VERSION_STRING}"

  cat > src/version.h <<EOF
// ScriptX version config files
// auto generated from the file VERSION
#define SCRIPTX_VERSION_STRING "${VERSION_STRING}"
#define SCRIPTX_VERSION_MAJOR ${VERSION_ARRAY[0]}
#define SCRIPTX_VERSION_MINOR ${VERSION_ARRAY[1]}
#define SCRIPTX_VERSION_PATCH ${VERSION_ARRAY[2]}

namespace script {

constexpr const char* kVersionString = SCRIPTX_VERSION_STRING;
constexpr int kVersionMajor = SCRIPTX_VERSION_MAJOR;
constexpr int kVersionMinor = SCRIPTX_VERSION_MINOR;
constexpr int kVersionPatch = SCRIPTX_VERSION_PATCH;

}  // namespace script

EOF

  git add src/version.h
}

function formatFile() {
  file=$1
  if [[ -f $file ]]; then
    # append license headers
    ${DEVTOOLS}/appendLicenseHeader.sh $file
    echo "clang-format $file"
    clang-format -i $file
    # stage changed
    git add $file
  fi
}

for file in $(git diff-index --cached --diff-filter=d --name-only HEAD); do
  # version file
  if [[ $file == "VERSION" ]]; then
    echo regenerate src/version.h from VERSION
    regenerateVersionHeader
    formatFile src/version.h
  fi

  # clang-format & license header
  if [[ $file =~ ${SOURCE_SUFFIX} ]]; then
    formatFile "$file"
  fi

done
